<template>
  <div style="height: 100%">
    <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
      <div class="header-container user-container" ref="headerContainer">
        <page-header :title="l('Tenants')"></page-header>
        <a-card :bordered="false">
          <a-form :layout="'vertical'" @submit.prevent="getSearchData">
            <a-row :gutter="8">
              <!-- 租户名称/租户代码 -->
              <a-col :sm="12">
                <a-form-item :label="l('TenantNameOrTenancyCode')">
                  <a-input-search
                    name="filterText"
                    :placeholder="l('SearchWithThreeDot')"
                    @search="getSearchData"
                    enterButton
                    v-model:value="filterText"
                  />
                </a-form-item>
              </a-col>
              <!-- 版本 -->
              <a-col :sm="12">
                <a-form-item :label="l('Edition')">
                  <edition-combo
                    :placeholder="l('PleaseSelect')"
                    :selectedEdition="selectedEdition"
                    @selectedEditionChange="selectedEditionChange($event)"
                  ></edition-combo>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="8" v-if="advancedFiltersVisible">
              <!-- 创建时间 -->
              <a-col :sm="12">
                <a-form-item :label="l('CreationTime')">
                  <a-range-picker
                    name="CreationDateRange"
                    :placeholder="[l('StartDateTime'), l('EndDateTime')]"
                    @change="createDateChange"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <!-- 操作部分 -->
          <a-row :gutter="8">
            <a-col :md="20" :sm="12">
              <a-button
                :type="'primary'"
                v-if="isGranted('Pages.Tenants.Create')"
                @click="createNewTenant"
              >
                <plus-outlined />
                <span>{{ l('CreateNewTenant') }}</span>
              </a-button>

              <a-button
                :type="'danger'"
                v-if="isGranted('Pages.Tenants.Delete')"
                @click="batchDelete"
              >
                <delete-outlined />
                <span>{{ l('BatchDelete') }}</span>
              </a-button>
            </a-col>

            <a-col :md="4" :sm="12" class="text-right">
              <a @click="advancedFiltersVisible = !advancedFiltersVisible">
                {{ advancedFiltersVisible ? l('HideAdvancedFilters') : l('ShowAdvancedFilters') }}
              </a>
            </a-col>
          </a-row>

          <!-- 数据部分 -->
          <div class="my-md">
            <a-alert :type="'info'" :showIcon="true">
              <template #message>
                <span v-html="l('GridSelectedXItemsTips', selectedRowKeys.length)"></span>
                <a @click="restCheckStatus()" class="ml-md">{{ l('ClearEmpty') }}</a>
                <a-divider type="vertical"></a-divider>
                <a @click="refresh()">{{ l('Refresh') }}</a>
              </template>
            </a-alert>
          </div>
        </a-card>
      </div>
      <!-- 表格 -->
      <div class="table-container">
        <a-table
          size="middle"
          :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data-source="dataList"
          :pagination="{
            total: totalItems,
            current: pageNumber,
            pageSize: pageSize,
            showTotal: showTotalInfo,
            showQuickJumper: true,
            showSizeChanger: true,
            change: pageNumberChange,
            showSizeChange: pageNumberChange,
            pageSizeOptions: pageSizeOptions,
            size: 'middle',
          }"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            checkAll: checkAll,
          }"
          @change="tableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'isActive'">
              <a class="isActive">
                <check-circle-two-tone v-if="record.isActive" />
                <close-circle-two-tone v-if="!record.isActive" two-tone-color="#eb2f96" />
              </a>
            </template>
            <template v-if="column.key === 'creationTime'">
              {{ _moment(record.creationTime) }}
            </template>
            <template v-if="column.key === 'Actions'">
              <!-- 修改 -->
              <a @click="edit(record)">
                <edit-outlined />
                <span>{{ l('Edit') }}</span>
                <a-divider type="vertical" />
              </a>
              <!-- 删除 -->
              <a-popconfirm
                placement="top"
                :okText="l('Ok')"
                :cancelText="l('Cancel')"
                @confirm="deleteItem(record)"
              >
                <template #title>{{ l('ConfirmDeleteWarningMessage') }}</template>
                <a>
                  <delete-outlined />
                  <span>{{ l('Delete') }}</span>
                  <a-divider type="vertical" />
                </a>
              </a-popconfirm>
              <!-- 更多 -->
              <a-dropdown>
                <a class="ant-dropdown-link">
                  {{ l('More') }}
                  <down-outlined />
                </a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      v-if="isGranted('Pages.Tenants.Impersonation')"
                      @click="tenantImpersonateLogin(record)"
                    >
                      <a href="javascript:;">
                        <login-outlined />
                        <span>{{ l('LoginAsThisTenant') }}</span>
                      </a>
                    </a-menu-item>
                    <a-menu-item
                      v-if="record.isActive && isGranted('Pages.Tenants.ChangeFeatures')"
                      @click="changeTenantFeatures(record)"
                    >
                      <a href="javascript:;">
                        <codepen-outlined />
                        <span>{{ l('Features') }}</span>
                      </a>
                    </a-menu-item>
                    <a-menu-item @click="unlockTenantAdminUser(record)">
                      <a href="javascript:;">
                        <unlock-outlined />
                        <span>{{ l('Unlock') }}</span>
                      </a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
          </template>
        </a-table>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { PagedListingComponentBase } from '/@/shared/component-base';
  import { EditionCombo } from '/@/app/admin-shared';
  import { defineComponent } from 'vue';
  import {
    PlusOutlined,
    DeleteOutlined,
    EditOutlined,
    LoginOutlined,
    CodepenOutlined,
    UnlockOutlined,
    CheckCircleTwoTone,
    CloseCircleTwoTone,
  } from '@ant-design/icons-vue';
  import { TenantServiceProxy, EntityDto, TenantListDto } from '/@/shared/service-proxies';
  import { CreateTenantComponent } from './create-tenant/index';
  import { EditTenantComponent } from './edit-tenant/index';
  import { CommonLookupComponent } from './common-lookup/index';
  import { EditTenantFeaturesComponent } from './edit-tenant-features/index';
  import { impersonationService } from '/@/shared/auth/index';
  import dayjs from 'dayjs';
  import 'dayjs/locale/zh-cn';
  import { IPagedRequestDto } from '/@/shared/component-base/interfaces';
  import { ColumnType } from 'ant-design-vue/lib/table';
  dayjs.locale('zh-cn');
  export default defineComponent({
    name: 'tenants',
    components: {
      EditionCombo,
      PlusOutlined,
      DeleteOutlined,
      EditOutlined,
      LoginOutlined,
      CodepenOutlined,
      UnlockOutlined,
      CheckCircleTwoTone,
      CloseCircleTwoTone,
      EditTenantFeaturesComponent,
    },
    mixins: [PagedListingComponentBase],
    data() {
      return {
        tenantService: new TenantServiceProxy(),
        selectedEdition: {
          value: 0,
        },
        advancedFiltersVisible: false, // 是否显示高级过滤
        // 请求参数
        editionId: undefined,
        subscribableDateRange: [null, null], // 订阅时间范围
        createDateRange: [null, null], // 创建时间范围
      };
    },
    methods: {
      // 获取列
      getColumns(): ColumnType<TenantListDto>[] {
        return [
          {
            title: 'No',
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('TenancyCodeName'),
            dataIndex: 'tenancyName',
            key: 'tenancyName',
            ellipsis: true,
          },
          {
            title: this.l('TenancyName'),
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
          },
          {
            title: this.l('Edition'),
            dataIndex: 'editionDisplayName',
            key: 'editionDisplayName',
            ellipsis: true,
          },
          {
            title: this.l('Active'),
            dataIndex: 'isActive',
            key: 'isActive',
            align: 'center',
            ellipsis: true,
          },
          {
            title: this.l('CreationTime'),
            dataIndex: 'creationTime',
            key: 'creationTime',
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
          },
          {
            title: this.l('Actions'),
            dataIndex: 'Actions',
            key: 'Actions',
            width: 250,
            align: 'center',
            ellipsis: true,
            fixed: 'right',
          },
        ];
      },
      /**
       * 获取数据
       */
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        this.tenantService
          .getPaged(
            this.advancedFiltersVisible ? this.subscribableDateRange[0] : undefined, // 订阅结束时间开始
            this.advancedFiltersVisible ? this.subscribableDateRange[1] : undefined, // 订阅结束时间结束
            this.advancedFiltersVisible ? this.createDateRange[0] : undefined, // 创建时间开始
            this.advancedFiltersVisible ? this.createDateRange[1] : undefined, // 创建时间结束
            this.editionId || undefined, // 版本id
            this.filterText, // 名称过滤字符串
            this.sorting, // 排序字段
            request.maxResultCount, // 最大数据量
            request.skipCount, // 跳过数据量
          )
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
          });
      },
      /**
       * 版本选择
       */
      selectedEditionChange(e: any): void {
        this.editionId = e ? e.value : null;
        this.getSearchData();
      },
      /**
       * 订阅日期改变
       */
      subscribableDateChange(e: any): void {
        if (!e) {
          this.subscribableDateRange = [null, null];
        } else {
          this.subscribableDateRange = e;
        }
        this.getSearchData();
      },
      /**
       * 创建时间改变
       */
      createDateChange(e: any): void {
        if (!e) {
          this.createDateRange = [null, null];
        } else {
          this.createDateRange = e;
        }
        this.getSearchData();
      },
      /**
       * 新建租户
       */
      createNewTenant() {
        this.modalHelper.create(CreateTenantComponent, null).subscribe((res) => {
          if (res) {
            this.refresh();
          }
        });
      },
      /**
       * 批量删除
       */
      batchDelete() {
        const selectCount = this.selectedRowKeys.length;
        if (selectCount <= 0) {
          this.message.warn(this.l('PleaseSelectAtLeastOneItem'));
          return;
        }
        let batchDeleteInput = this.selectedRowKeys.map((o) => {
          return new EntityDto({ id: o });
        });
        this.message.confirm(
          this.l('ConfirmDeleteXItemsWarningMessage', selectCount),
          '',
          (res: any) => {
            if (res) {
              this.tenantService
                .batchDelete(batchDeleteInput)
                .finally(() => {
                  this.isTableLoading = false;
                })
                .then(() => {
                  this.refresh();
                });
            }
          },
        );
      },
      /**
       * 单个删除
       */
      deleteItem(item: TenantListDto): void {
        this.isTableLoading = true;
        this.tenantService
          .delete(item.id)
          .finally(() => {
            this.isTableLoading = false;
          })
          .then(() => {
            this.refresh();
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
      },
      /**
       * 编辑
       */
      edit(item: TenantListDto): void {
        this.modalHelper.create(EditTenantComponent, { entityId: item.id }).subscribe((res) => {
          if (res) {
            this.refresh();
          }
        });
      },
      /**
       * 使用此租户登录
       */
      tenantImpersonateLogin(item: TenantListDto): void {
        this.modalHelper.create(CommonLookupComponent, { tenantId: item.id }).subscribe((res) => {
          if (res) {
            this.impersonateUser(res, item.id);
          }
        });
      },
      /**
       * 特性参数列表
       */
      changeTenantFeatures(item: TenantListDto): void {
        this.modalHelper
          .create(EditTenantFeaturesComponent, { tenantId: item.id })
          .subscribe((res) => {
            if (res) {
              this.refresh();
            }
          });
      },
      /**
       * 解锁
       */
      unlockTenantAdminUser(item: TenantListDto): void {
        this.isTableLoading = true;
        this.tenantService
          .unlockTenantAdmin(item)
          .finally(() => {
            this.isTableLoading = false;
          })
          .then(() => {
            this.notify.success(this.l('UnlockedTenandAdmin'));
          });
      },
      impersonateUser(item, id) {
        impersonationService.impersonate(parseInt(item.value), id);
      },
    },
  });
</script>
